/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import DAL.DABasic;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import model.FileList;
import object.CD;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 *
 * @author HOANG ANH
 */
@ManagedBean
@SessionScoped
public class MainController {

    private String xmlFile = "";
    private String xsltFile = "";
    private String schemaFile = "";
    private String result = "";
    private String checkMassage = "";
    private boolean readReady = false;
    private boolean checkReady = false;
    private boolean dbReady = false;
    @ManagedProperty(value = "#{fileList}")
    private FileList fileList;

    public FileList getFileList() {
        return fileList;
    }

    public void setFileList(FileList fileList) {
        this.fileList = fileList;
    }

    public boolean isCheckReady() {

        if (!xmlFile.equals("") && !schemaFile.equals("")) {
            checkReady = true;
        } else {
            checkReady = false;
        }
        return checkReady;
    }

    public void setCheckReady(boolean checkReady) {
        this.checkReady = checkReady;
    }

    public boolean isDbReady() {

        if (!xmlFile.equals("")) {
            dbReady = true;
        } else {
            dbReady = false;
        }
        return dbReady;
    }

    public void setDbReady(boolean dbReady) {
        this.dbReady = dbReady;
    }

    public boolean isReadReady() {
        if (!xmlFile.equals("") && !xsltFile.equals("")) {
            readReady = true;
        } else {
            readReady = false;
        }
        return readReady;
    }

    public void setReadReady(boolean readReady) {
        this.readReady = readReady;
    }

    public String getSchemaFile() {
        return "<i>" + schemaFile + "</i>";
    }

    public String getSchemaFileContent() {
        return fileList.getSchemaList().get(schemaFile);
    }

    public void setSchemaFile(String schemaFile) {
        this.schemaFile = schemaFile;
    }

    public String getXmlFile() {
        return "<i>" + xmlFile + "</i>";
    }

    public String getXmlFileContent() {
        return fileList.getXmlList().get(xmlFile);
    }

    public void setXmlFile(String xmlFile) {
        this.xmlFile = xmlFile;
    }

    public String getXsltFile() {
        return "<i>" + xsltFile + "</i>";
    }

    public String getXsltFileContent() {
        return fileList.getXsltList().get(xsltFile);
    }

    public void setXsltFile(String xsltFile) {
        this.xsltFile = xsltFile;
    }

    /** Creates a new instance of MainController */
    public MainController() {
    }

    public void uploadReadFiles(FileUploadEvent e) {
        UploadedFile file = e.getFile();
        String name = file.getFileName();
        String extension = name.substring(name.lastIndexOf(".") + 1);
        if (extension.equals("xml")) {
            xmlFile = name;
            Map list = fileList.getXmlList();
            list.put(file.getFileName(), new String(file.getContents()));
            fileList.setXmlList(list);
        } else if (extension.equals("xslt") || extension.equals("xsl")) {
            xsltFile = name;
            Map list = fileList.getXsltList();
            list.put(file.getFileName(), new String(file.getContents()));
            fileList.setXsltList(list);
        }
    }

    public String ReadXML() {
        try {
            StringReader xsltReader = new StringReader(fileList.getXsltList().get(xsltFile));
            StringReader xmlReader = new StringReader(fileList.getXmlList().get(xmlFile));

            Source xsltSource = new StreamSource(xsltReader);

            Transformer transform = TransformerFactory.newInstance().newTransformer(xsltSource);

            Source xmlSource = new StreamSource(xmlReader);

            StringWriter outWriter = new StringWriter();
            Result rs = new StreamResult(outWriter);

            transform.transform(xmlSource, rs);


            result = new String(outWriter.getBuffer());
            System.out.println(result);

            return "result";
        } catch (Exception ex) {

            ex.printStackTrace();
            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, error);
            return null;
        }
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public void uploadCheckFiles(FileUploadEvent e) {
        UploadedFile file = e.getFile();
        String name = file.getFileName();
        String extension = name.substring(name.lastIndexOf(".") + 1);
        if (extension.equals("xml")) {
            xmlFile = name;
            Map list = fileList.getXmlList();
            list.put(file.getFileName(), new String(file.getContents()));
            fileList.setXmlList(list);
        } else if (extension.equals("xsd")) {
            schemaFile = name;
            Map list = fileList.getSchemaList();
            list.put(file.getFileName(), new String(file.getContents()));
            fileList.setSchemaList(list);
        }


    }

    public void checkXML() {
        try {

            Source xmlSource = new StreamSource(new StringReader(fileList.getXmlList().get(xmlFile)));
            Source schemaSource = new StreamSource(new StringReader(fileList.getSchemaList().get(schemaFile)));

            Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaSource);

            Validator validator = schema.newValidator();

            validator.validate(xmlSource);

            FacesMessage ok = new FacesMessage(FacesMessage.SEVERITY_INFO, "Checked!", "XML validated!");
            FacesContext.getCurrentInstance().addMessage(null, ok);

        } catch (Exception ex) {

            ex.printStackTrace();
            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, error);
        }
    }

    public String getCheckMessage() {
        return checkMassage;
    }

    public void setCheckMessage(String checkResult) {
        this.checkMassage = checkResult;
    }

    public void uploadXMLFiles(FileUploadEvent e) {
        UploadedFile file = e.getFile();
        String name = file.getFileName();
        String extension = name.substring(name.lastIndexOf(".") + 1);
        if (extension.equals("xml")) {
            xmlFile = name;
            Map list = fileList.getXmlList();
            list.put(file.getFileName(), new String(file.getContents()));
            fileList.setXmlList(list);
        }
    }

    public void importToDatabase() {
        try {

            InputSource xmlSource = new InputSource(new StringReader(fileList.getXmlList().get(xmlFile)));
            Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlSource);


            NodeList cdList = dom.getElementsByTagName("cd");

            if (cdList.getLength() == 0) {
                FacesMessage ok = new FacesMessage(FacesMessage.SEVERITY_WARN, "No CD Found!", "Please Check Your XML File Again!");
                FacesContext.getCurrentInstance().addMessage(null, ok);
                return;
            }

            for (int i = 0; i < cdList.getLength(); i++) {
                Element element = (Element) cdList.item(i);
                CD cd = new CD();
                cd.setTitle(element.getElementsByTagName("title").item(0).getTextContent());
                cd.setArtist(element.getElementsByTagName("artist").item(0).getTextContent());
                cd.setCountry(element.getElementsByTagName("country").item(0).getTextContent());
                cd.setCompany(element.getElementsByTagName("company").item(0).getTextContent());
                cd.setPrice(Float.parseFloat(element.getElementsByTagName("price").item(0).getTextContent()));
                cd.setYear(element.getElementsByTagName("year").item(0).getTextContent());

                DABasic.insertCD(cd);
            }

            DABasic.closeCon();

            FacesMessage ok = new FacesMessage(FacesMessage.SEVERITY_INFO, "Success!", "Import Completed!");
            FacesContext.getCurrentInstance().addMessage(null, ok);

        } catch (Exception ex) {

            ex.printStackTrace();
            FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, error);

        }

    }
}
